/*
 * Copyright (C) 2019-2020 Alibaba Group Holding Limited
 */

#include <yoc/lpm.h>

#include "app_main.h"
#include "app_sys.h"
#define YEAR                                                                              \
    ((((__DATE__[7] - '0') * 10 + (__DATE__[8] - '0')) * 10 + (__DATE__[9] - '0')) * 10 + \
     (__DATE__[10] - '0'))

#define MONTH                                            \
    (__DATE__[2] == 'n'   ? 0                            \
     : __DATE__[2] == 'b' ? 1                            \
     : __DATE__[2] == 'r' ? (__DATE__[0] == 'M' ? 2 : 3) \
     : __DATE__[2] == 'y' ? 4                            \
     : __DATE__[2] == 'n' ? 5                            \
     : __DATE__[2] == 'l' ? 6                            \
     : __DATE__[2] == 'g' ? 7                            \
     : __DATE__[2] == 'p' ? 8                            \
     : __DATE__[2] == 't' ? 9                            \
     : __DATE__[2] == 'v' ? 10                           \
                          : 11)

#define DAY ((__DATE__[4] == ' ' ? 0 : __DATE__[4] - '0') * 10 + (__DATE__[5] - '0'))

#define APP_VERSION "app-1.6.6-8"
#define VERSION_MAX_LEN (30) //app-1.6.6-8-20210819.152056

static int boot_reason = -1;

void app_sys_reboot()
{
    app_sys_set_boot_reason(BOOT_REASON_SOFT_RESET);
    aos_reboot();
}

int app_sys_set_boot_reason(int reason)
{
    CHECK_PARAM(reason < BOOT_REASON_NONE && reason >= BOOT_REASON_SOFT_RESET, -1);
    int ret;
    int cur_reason;

    ret = aos_kv_getint("SYS_BOOT_REASON", &cur_reason);
    if (ret != 0 || cur_reason != reason) {
        boot_reason = reason;
        ret         = aos_kv_setint("SYS_BOOT_REASON", reason);
        CHECK_RET_WITH_RET(ret == 0, -1);
    }

    return 0;
}

int app_sys_get_boot_reason()
{
    return boot_reason;
}

void app_sys_init()
{
    int reason;
    int ret;

    ret = aos_kv_getint("SYS_BOOT_REASON", &reason);
    if (ret != 0 || reason >= BOOT_REASON_NONE || reason < BOOT_REASON_SOFT_RESET) {
        reason = BOOT_REASON_POWER_ON;
    }

    aos_kv_setint("SYS_BOOT_REASON", BOOT_REASON_POWER_ON);
    boot_reason = reason;
}

char *aos_get_app_version(void)
{
    static char version[VERSION_MAX_LEN] = {0};
    if (version[0] == 0)
    {
        memset(version, 0, sizeof(version));
        char time[10] = __TIME__; //12:31:15
        int count = 0;
        for (int i = 0; i < strlen(time); i++)
            if (time[i] != ':')
                time[count++] = time[i]; // here count is incremented
        time[count] = '\0';
        sprintf(version, "%s-%d%02d%02d.%s", APP_VERSION, YEAR, MONTH + 1, DAY, time);
    }
    return version; //app-1.6.6-8-20210819.152056
}